﻿using System.Collections;
using System.Collections.Concurrent;
using System.Net.WebSockets;

namespace Md.Api.Model.Ws.Request;
/// <summary>
/// 用户通讯实体类
/// </summary>
public class RequestUserConnectionModel : IEnumerable<KeyValuePair<string, WebSocket>>
{
    /// <summary>
    /// 用户组
    /// </summary>
	private ConcurrentDictionary<string, WebSocket> _users = new ConcurrentDictionary<string, WebSocket>();

    /// <summary>
    /// 用户数
    /// </summary>
    public int Count => _users.Count;

    /// <summary>
    /// 添加用户
    /// </summary>
    /// <param name="userId">用户编号</param>
    /// <param name="webSocket">通讯</param>
    /// <returns>WebSocket</returns>
    public WebSocket GetOrAdd(string userId, WebSocket webSocket)
    {
        return _users.GetOrAdd(userId, webSocket);
    }

    /// <summary>
    /// 获取用户
    /// </summary>
    /// <param name="userId">用户编号</param>
    /// <param name="webSocket">通讯</param>
    /// <returns>bool</returns>
    public bool TryGetValue(string userId,out WebSocket webSocket)
    {
        return _users.TryGetValue(userId, out webSocket);
    }

    /// <summary>
    /// 删除用户
    /// </summary>
    /// <param name="userId">用户编号</param>
    /// <param name="webSocket">通讯</param>
    /// <returns></returns>
    public bool TryRemove(string userId,out WebSocket webSocket)
    {
        return _users.TryRemove(userId, out webSocket);
    }

    /// <summary>
    /// 清除所有用户
    /// </summary>
    public void Clear()
    {
        _users.Clear();
    }

    /// <summary>
    /// 获取用户组列表
    /// </summary>
    /// <returns>IEnumerator<KeyValuePair<string, WebSocket>></returns>
    public IEnumerator<KeyValuePair<string, WebSocket>> GetEnumerator()
    {
        return _users.GetEnumerator();
    }

    /// <summary>
    /// 获取用户组列表
    /// </summary>
    /// <returns></returns>
    IEnumerator IEnumerable.GetEnumerator()
    {
        return _users.GetEnumerator();
    }
}

